import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import notification from 'ant-design-vue/es/notification'
// import getPageTitle from '@/utils/get-page-title'
import {
  getStore
} from '@/utils/store'
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
// var token = getStore({ name: "access_token" })
// var hasToken = store.getters.token
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  const hasToken = getStore({
    name: 'access_token'
  })

  if (hasToken) {
    if (to.path === '/user/login') {
      // if is logged in, redirect to the home page
      next({
        path: '/'
      })

      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        console.log(store)
        store.dispatch('GetInfo').then(data => {
          console.log(data)
          store.dispatch('permission/generateRoutes').then(accessRoutes => {
            console.log(accessRoutes)
            router.addRoutes(accessRoutes)
            next({
              ...to,
              replace: true
            })
          })
        }).catch(() => {
          notification.error({
            message: '错误',
            description: '请求用户信息失败，请重试'
          })
          store.dispatch('Logout').then(() => {
            next(`/login?redirect=${to.path}`)
          })
        })
      } else {
        next()
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
